package com.treasure.mall.biz.service.core.live.impl;

import com.treasure.mall.biz.base.RedisTemplate;
import com.treasure.mall.biz.config.redis.RedisConstant;
import com.treasure.mall.biz.dto.live.LiveMessageUserLevel;
import com.treasure.mall.biz.dto.live.LiveRobotConfigDTO;
import com.treasure.mall.biz.entity.live.LiveRobotPO;
import com.treasure.mall.biz.entity.live.LiveSessionPO;
import com.treasure.mall.biz.remote.live.TencentIMService;
import com.treasure.mall.biz.remote.live.TencentTools;
import com.treasure.mall.biz.remote.live.dto.JoinMessageDTO;
import com.treasure.mall.biz.repository.live.LiveRobotRepository;
import com.treasure.mall.biz.service.core.live.LiveRobotService;
import com.treasure.mall.biz.service.core.live.LiveSessionService;
import com.treasure.mall.zbq.common.constant.Constant;
import com.treasure.mall.zbq.common.ienum.live.LiveEnums;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Random;

/**
 *
 * 机器人接口
 * +---------------------------------------------------------
 * * @package: com.treasure.mall.biz.service.core.live.impl
 * * @author: guomw (guomwchen@foxmail.com)
 * * @date: 2020/7/3 10:50
 * * @since: V1.0.0
 * +---------------------------------------------------------
 * 注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的
 * Copyright 2019-2022 com.treasure.mall.biz.service.core.live.impl Inc. All rights reserved.
 */
@Slf4j
@Service
public class LiveRobotServiceImpl implements LiveRobotService {
    private Random random = new Random(System.currentTimeMillis());


    @Autowired
    private LiveRobotRepository robotRepository;
    @Autowired
    private TencentIMService tencentIMService;
    @Autowired
    private LiveSessionService liveSessionService;
    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;
    @Resource
    private RedisTemplate redisTemplate;


    @Override
    public void startAutoJoin(Long roomId) {
        LiveRobotConfigDTO robotConfigDTO = new LiveRobotConfigDTO();
        robotConfigDTO.setLiveRoomId(roomId);
        robotConfigDTO.setEnable(true);
        robotConfigDTO.setMin(10);
        robotConfigDTO.setMax(300);
        this.startAutoJoin(robotConfigDTO);
    }

    /**
     * 开启机器人自动加入房间
     *
     * @param dto
     */
    @Override
    public void startAutoJoin(LiveRobotConfigDTO dto) {
        LiveSessionPO sessionPO = liveSessionService.getCurrentSession(dto.getLiveRoomId());
        if (sessionPO == null || sessionPO.getPlayStatus() != LiveEnums.PlayStatus.PAYING || sessionPO.getEnableRobot()) {
            return;
        }
        //开启记录
        liveSessionService.enableRobot(sessionPO.getId(), true);
        this.setPlayStatus(sessionPO.getId(), true);
        // 发送开始直播消息
        threadPoolTaskExecutor.execute(() -> startSendMessage(dto, sessionPO.getId(), 0));
    }

    /**
     * 停止机器人
     *
     * @param roomId
     */
    @Override
    public void stop(Long roomId) {
        LiveSessionPO sessionPO = liveSessionService.getCurrentSession(roomId);
        if (sessionPO == null) {
            return;
        }
        liveSessionService.enableRobot(sessionPO.getId(), false);
        this.setPlayStatus(sessionPO.getId(), false);
    }

    /**
     * 开始发送机器人消息
     *
     * @param sessionId
     * @param page
     */
    private void startSendMessage(LiveRobotConfigDTO config, String sessionId, int page) {
        Page<LiveRobotPO> robots = robotRepository.findAll(PageRequest.of(page, Constant.DEFAULT_PAGE_SIZE));
        List<LiveRobotPO> list = robots.getContent();
        for (LiveRobotPO robotPO : list) {
            try {
                tencentIMService.join(JoinMessageDTO.builder()
                        .liveSessionId(sessionId)
                        .name(robotPO.getNickName())
                        .level(new LiveMessageUserLevel(robotPO))
                        .build());

                liveSessionService.addActivityNum(sessionId);
                Thread.sleep((random.nextInt(config.getMax()) + config.getMin()) * 1000);
            } catch (Exception e) {
                log.error("startSendMessage", e);
            }
            if (!isPlayStatus(sessionId)) {
                break;
            }
        }


        try {
            if (list.size() > 0) {
                Thread.sleep(2000);
                LiveSessionPO sessionPO = liveSessionService.findById(sessionId);
                if (sessionPO != null && sessionPO.getPlayStatus() == LiveEnums.PlayStatus.PAYING && sessionPO.getEnableRobot()) {
                    startSendMessage(config, sessionId, page + 1);
                }
            }
        } catch (Exception e) {
            log.error("startSendMessage", e);
        }
    }

    @Override
    public void setPlayStatus(String sessionId, boolean start) {
        String robotStatusKey = RedisConstant.KEY_LIVE_SESSION + sessionId + ":robot";
        redisTemplate.opsForHash().put(robotStatusKey, RedisConstant.HASH_KEY_RO_BOT_STATUS, start ? 1 : 0);
        if (!start) {
            redisTemplate.opsForHash().delete(robotStatusKey, RedisConstant.HASH_KEY_RO_BOT_STATUS);
        }
    }

    /**
     * 获取指定直播间是否开启机器人
     *
     * @param sessionId
     * @return
     */
    @Override
    public boolean isPlayStatus(String sessionId) {
        try {
            String robotStatusKey = RedisConstant.KEY_LIVE_SESSION + sessionId + ":robot";
            return redisTemplate.getInt(robotStatusKey, RedisConstant.HASH_KEY_RO_BOT_STATUS) == 1;
        } catch (Exception e) {
            return false;
        }
    }
}
